#pragma once
#include <etcd/Value.hpp>
#include <etcd/Response.hpp>
#include <etcd/Client.hpp>
#include <etcd/KeepAlive.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include<string>
////////////////////////////////////////////////
//服务注册，部署微服务的服务器上使用此代码注册服务
////////////////////////////////////////////////
namespace etcdtools
{
    class Register
    {
        private:
        etcd::Client cli;
        std::shared_ptr<etcd::KeepAlive> keep_alive;
        
        public:
        //etcd服务器的ip地址和端口
        Register(const std::string& server_url)
        :cli(server_url)
        {}
        //微服务的名称，ip地址和端口号
        bool regist(const std::string& service_name,const std::string& url)
        {
            keep_alive=cli.leasekeepalive(3).get();//创建保活对象，自动续约机制
            auto lease_id=keep_alive->Lease();//获取租约id

            //拼接唯一id，作为机器实例名称
            boost::uuids::uuid uuid = boost::uuids::random_generator()();
            std::string instance=boost::uuids::to_string(uuid).substr(0,8);
            string sername=service_name+"/"+instance;

            auto pplx=cli.put(sername,url,lease_id);//异步对象，不调用Wait会立刻返回
            auto ret=pplx.wait();//调用wait，阻塞等待结果返回
            if(ret==pplx::task_status::completed)
            {
                return pplx.get().is_ok();
            }
            return false;
        }
    };
}